import { UploadOutlined } from '@ant-design/icons';
import {Button, Card, Col, Form, message, Row, Select, Space, Upload, Typography, Spin} from 'antd';
import {
  genChartByAiAsyncUsingPost,
  genChartByAiUsingPost,
  listChartByPageUsingPost
} from '@/services/xiBI/chartController';
import React, { useEffect, useState } from 'react';
import type { UploadProps } from 'antd';
import {useForm} from "antd/es/form/Form";

const { Option } = Select;
const { Title } = Typography;

const AddChartAsync: React.FC = () => {
  const [form] = useForm();
  const [chart, setChart] = useState<API.BiResponse>();
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [option, setOption] = useState<any>();

  const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

  // 上传前的校验函数
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    // 校验文件类型
    const isExcel =
      file.type === 'application/vnd.ms-excel' ||
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isExcel) {
      message.error('只能上传 Excel 文件');
      return Upload.LIST_IGNORE; // 阻止上传
    }

    // 校验文件大小
    if (file.size > MAX_FILE_SIZE) {
      message.error(`文件大小不能超过 ${MAX_FILE_SIZE / 1024 / 1024}MB`);
      return Upload.LIST_IGNORE; // 阻止上传
    }

    return true; // 允许上传
  };

  useEffect(() => {
    listChartByPageUsingPost({}).then((res) => {
      console.error('res', res);
    });
  }, []);

  const onFinish = async (values: any) => {
    if (submitting) {
      return;
    }
    setOption(undefined);
    setChart(undefined);
    setSubmitting(true);
    const params = {
      ...values,
      file: undefined,
    };
    try {
      const res = await genChartByAiAsyncUsingPost(params, {}, values.file.file.originFileObj);
      if (!res?.data) {
        message.error('分析错误');
      } else {
        message.success('分析成功,稍后请在我的图表页面查看');
        form.resetFields();
      }
    } catch (e: any) {
      message.error('分析失败' + e.message);
    }
    setSubmitting(false);
  };

  return (
    <div className="add-chart-async" style={{ padding: '24px' }}>
      <Row gutter={[24, 24]}>
        <Col xs={24} md={12}>
          <Card
            title={
              <Title level={4} style={{ marginBottom: 0 }}>
                智能分析
              </Title>
            }
            bordered={false}
            style={{ boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)', borderRadius: '8px' }}
          >
            <Form form={form}
              name="validate_other"
              onFinish={onFinish}
              initialValues={{
                'input-number': 3,
                'checkbox-group': ['A', 'B'],
                rate: 3.5,
                'color-picker': null,
              }}
              layout="vertical"
            >
              <Form.Item
                name="goal"
                label={<span style={{ fontWeight: 'bold' }}>分析目标</span>}
                rules={[{ required: true, message: '请输入分析目标' }]}
              >
                <textarea
                  placeholder="请输入你的分析需求"
                  style={{ width: '100%', minHeight: '100px', padding: '8px', borderRadius: '4px', border: '1px solid #d9d9d9' }}
                />
              </Form.Item>
              <Form.Item
                name="name"
                label={<span style={{ fontWeight: 'bold' }}>图表名称</span>}
              >
                <input
                  placeholder="请输入图表名称"
                  style={{ width: '100%', padding: '8px', borderRadius: '4px', border: '1px solid #d9d9d9' }}
                />
              </Form.Item>
              <Form.Item
                name="chartType"
                label={<span style={{ fontWeight: 'bold' }}>图表类型</span>}
                rules={[{ required: true, message: '请选择图表类型' }]}
              >
                <Select placeholder="请选择图表类型" style={{ width: '100%' }}>
                  <Option value="折线图">折线图</Option>
                  <Option value="饼状图">饼状图</Option>
                  <Option value="柱状图">柱状图</Option>
                  <Option value="散点图">散点图</Option>
                  <Option value="雷达图">雷达图</Option>
                  <Option value="地理坐标">地理坐标</Option>
                  <Option value="k线图">k线图</Option>
                  <Option value="关系图">关系图</Option>
                  <Option value="平行坐标系">平行坐标系</Option>
                  <Option value="盒须图">盒须图</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="file"
                label={<span style={{ fontWeight: 'bold' }}>上传数据</span>}
                extra="请上传 Excel 文件"
              >
                <Upload name="file" beforeUpload={beforeUpload}>
                  <Button icon={<UploadOutlined />} style={{ width: '100%' }}>
                    点击上传
                  </Button>
                </Upload>
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={submitting}
                    disabled={submitting}
                    style={{ width: '120px' }}
                  >
                    智能分析
                  </Button>
                  <Button htmlType="reset" style={{ width: '120px' }}>
                    重新输入
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default AddChartAsync;
